using System;
using System.Globalization;
using System.Threading;
using Nullables;
using Spring.Core;
using Spring.Objects;

namespace Sedna.Core.Controls.Actions.Support
{
	/// <summary>
	/// Summary description for NullableUtil.
	/// </summary>
	public class NullablesUtil
	{
		private NullablesUtil()
		{
		}

		public static NullableDecimal ToNullableDecimal(object value)
		{
			return ToNullableDecimal(value, false);
		}

		public static NullableDecimal ToNullableDecimal(object value, bool throwException)
		{
			if (value==null)
			{
				return null;
			}
			if (value is decimal)
			{
				return (decimal)value;
			}
			if (value is NullableDecimal)
			{
				return (NullableDecimal)value;
			}
			if (!throwException)
			{
				return null;
			}
			throw new TypeMismatchException(String.Format("Cannot convert \"{0}\" to NullableDecimal.", value));
		}
		
		public static NullableInt32 ToNullableInt32(object value)
		{
			return ToNullableInt32(value, false);
		}

		public static NullableInt32 ToNullableInt32(object value, bool throwException)
		{
			if (value==null)
			{
				return null;
			}
			if (value is NullableInt32)
			{
				return (NullableInt32)value;
			}
			if (value is Int32)
			{
				return (Int32)value;
			}
			if (!throwException)
			{
				return null;
			}
			throw new TypeMismatchException(String.Format("Cannot convert \"{0}\" to NullableInt32.", value));
		}

		public static object ToObject(INullableType value)
		{
			if (value==null||!value.HasValue)
			{
				return null;
			}
			return value.Value;
		}

		public static NullableInt32 ParseNullableInt32(string str)
		{
			return ParseNullableInt32(str, Thread.CurrentThread.CurrentCulture, false);	
		} 

		public static NullableInt32 ParseNullableInt32(string str, IFormatProvider formatProvider, bool throwException)
		{
			try
			{
				return Int32.Parse(str, NumberStyles.Number, formatProvider);
			}	
			catch
			{
				if (!throwException)
				{
					return null;
				}
				throw;
			}
		} 


	}
}
